import Lazyimg from './Lazyimg';
import { getScrollParent } from './utils';

//设计思想：柯里化函数，使用Lazy类时还可以访问Lazyload函数作用域内的属性和方法
export default function Lazyload(Vue) {
  return class Lazy {
    constructor(options) {
      this.options = options;
      //flag
      this.isAddScrollListener = false;
      //该池子保存所有实例
      this.lazyImgPool = [];
    }

    bindLazy(el, bindings, vnode) {
      // console.log(el);
      //<img alt="xxxxxxxxxx"/>

      /**
         console.log(bindings);
         * {
         *   name: 'lazy',
         *   rawName: 'v-lazy',
         *   value: 'http://localhost:3000/images/1.jpg',
         *   expression: 'item.src',
         *   modifiers: {},
         *   def: {bind: ƒ}
         * }
         */

      // console.log(vnode);
      //VNode {tag: 'img', data: {…}, children: undefined, text: undefined, elm: img, …}

      //为什么使用nextTick? 因为bind时dom节点还没渲染出来
      Vue.nextTick(() => {
        //找到有写overflow: auto/scroll 的节点
        const scrollParent = getScrollParent(el);
        // console.log(scrollParent);
        //<div class="container"></div>

        //绑定滚动事件处理函数
        if (scrollParent && !this.isAddScrollListener) {
          scrollParent.addEventListener(
            'scroll',
            this.handleScroll.bind(this),
            false
          );
        }

        //图片实例
        const lazyImg = new Lazyimg({
          el,
          src: bindings.value,
          options: this.options,
          imgRender: this.imgRender,
        });

        //缓存到池子里
        this.lazyImgPool.push(lazyImg);

        //首次加载
        this.handleScroll();

        // console.log(this.lazyImgPool);
        //[Lazyimg, Lazyimg, Lazyimg, Lazyimg, ...]
      });
    }

    handleScroll() {
      let isVisible = false;

      //遍历每一个图片地址实例
      this.lazyImgPool.forEach((lazyImg) => {
        //图片没有加载时
        if (!lazyImg.loaded) {
          //检查
          isVisible = lazyImg.checkIsVisible();
          //加载图片
          isVisible && lazyImg.loadImg();
        }
      });
    }

    //渲染地址
    imgRender(lazyImg, state) {
      const { el, options } = lazyImg;
      const { loading, error } = options;
      let src = '';

      switch (state) {
        case 'loading':
          //如果用户有填写loading就用用户的否则为空
          src = loading || '';
          break;
        case 'error':
          src = error || '';
          break;
        default:
          src = lazyImg.src;
          break;
      }

      //给节点增加src attribute属性
      el.setAttribute('src', src);
    }
  };
}
